//
//  KeyChain.m
//  ONENIGHT
//
//  Created by FLY on 2018/7/30.
//  Copyright © 2018年 FLY. All rights reserved.
//

#import "KeyChain.h"
#import <UIKit/UIKit.h>

#define UUID_IPhoneKEY @"UUIDKEY_myuuid"

@implementation KeyChain

+ (NSString *)getUUID{
    NSString *uuid = [KeyChain getUUIDFromKeyChain];
    if (uuid == nil) {
        uuid = [[UIDevice currentDevice] identifierForVendor].UUIDString;
        [KeyChain saveUUID:uuid];
    }
    NSLog(@"uuid___%@",uuid);
    return uuid;
}

+ (NSString *)getUUIDFromKeyChain{
    NSString *server = [[NSBundle mainBundle] bundleIdentifier];
    NSDictionary *queueDict = @{
                                (__bridge id)kSecClass:(__bridge id)kSecClassGenericPassword,
                                (__bridge id)kSecAttrService:server,
                                (__bridge id)kSecAttrAccount:UUID_IPhoneKEY,
                                (__bridge id)kSecReturnData:(__bridge id)kCFBooleanTrue
                                /*(__bridge id)kSecMatchLimit : (__bridge id)kSecMatchLimitAll
                                 当为kSecMatchLimit时，SecItemCopyMatching第二个参数为CFArrayRef，元素为CFDataRef*/
                                };
    CFDataRef dataRef = NULL;
    OSStatus state = SecItemCopyMatching((__bridge CFDictionaryRef)queueDict, (CFTypeRef*)&dataRef);
    
    NSString *value = nil;
    if (state == errSecSuccess) {
        value = [[NSString alloc] initWithData:(__bridge_transfer NSData*)dataRef encoding:NSUTF8StringEncoding];
    }
    
    return value;
}

+ (void)saveUUID:(NSString *)uuid{
    NSData *valueData = [uuid dataUsingEncoding:NSUTF8StringEncoding];
    NSString *service = [[NSBundle mainBundle] bundleIdentifier];
    NSDictionary *dict = @{
                           (__bridge id)kSecClass:(__bridge id)kSecClassGenericPassword,
                           (__bridge id)kSecAttrService:service,
                           (__bridge id)kSecAttrAccount:UUID_IPhoneKEY,
                           (__bridge id)kSecValueData:valueData
                           };
    CFTypeRef typeResult = NULL;
    OSStatus state =  SecItemAdd((__bridge CFDictionaryRef)dict, &typeResult);
    if (state == errSecSuccess) {
        NSLog(@"store_succeed");
    }else{
        NSLog(@"store_fail");
    }
    
}
@end
